from django.contrib.auth.backends import ModelBackend, UserModel
from django.db.models import Q
from rest_framework_jwt.utils import jwt_payload_handler as payload_handler
# 自定义载荷信息
# 重写底层的方法 jwt_payload_handler
def jwt_payload_handler(user):
    print("jwt_payload_hander被执行")
    # 1.加载原来的payload
    payload = payload_handler(user)
    # 2.追加自己的信息
    if hasattr(user, 'avatar'):
       payload['avatar'] = user.avatar
    if isinstance(user,"money"):
       payload['money'] = float(user.money)

    return payload


# 自定义登录方式-可以通过手机号或邮箱登录
class CustomAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 根据用户的手机号，邮箱进行验证
        # 先对用户名和密码进行有效性校验
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        # 根据username进行查询(注意: 此时的username可能表示的是用户名，手机号，邮箱)
        user=UserModel.objects.filter(Q(username=username)|Q(mobile=username)|Q(email=username)).first()
        # 校验密码
        if user and user.check_password(password) and self.user_can_authenticate(user):
            # 登录成功
            return user























